//
//  ZHPlayViewController.m
//  XMLYFM
//
//  Created by dllo on 15/12/26.
//  Copyright © 2015年 zzl. All rights reserved.
//

#import "ZHPlayViewController.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "AppTools.h"
#import "ZTAlbumModel.h"
#import "ZTTrackModel.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "ZHPlayListViewController.h"
#import "ZHPlayButtonView.h"

@interface ZHPlayViewController ()

@property(nonatomic,retain)UIImageView *ownerAvator;
@property(nonatomic,retain)UILabel *ownerName;
@property(nonatomic,retain)UILabel *ownerInfo;
@property(nonatomic,assign)NSInteger uid;

@end

@implementation ZHPlayViewController

//将player页设成单例
+(instancetype)sharaMusicPlayer
{
    static ZHPlayViewController *playerVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        playerVC = [[ZHPlayViewController alloc] init];
        
    });
    
    return playerVC;
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
//    NSLog(@"ssss%ld",self.player.state);
    if (self.player.state == STKAudioPlayerStatePlaying || self.player.state == STKAudioPlayerStateReady) {
        
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_pause_n_p@2x.png"] forState:UIControlStateNormal];
    } else if (self.player.state == STKAudioPlayerStatePaused){
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_play_n_p@2x.png"] forState:UIControlStateNormal];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    _playerView = [[ZHPlayerView alloc] initWithFrame:[[UIScreen mainScreen]bounds]];
    [self.view addSubview:self.playerView];
    
    [self createViews];
    
    _player = [[STKAudioPlayer alloc]initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    self.player.volume = 0.5;
    
    //    self.title.
    
    
    // 返回
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.backgroundColor = [UIColor clearColor];
//    backButton.backgroundColor = [UIColor grayColor];
    backButton.frame = CGRectMake(10, 40, 40, 30);

    [backButton setImage:[UIImage imageNamed:@"navidrop_arrow_down_n@2x.png"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"navidrop_arrow_down_h@2x.png"] forState:UIControlStateHighlighted];
    
     UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    moreButton.frame = CGRectMake(0, 0, 40, 30);
    moreButton.backgroundColor = [UIColor clearColor];
//    moreButton.backgroundColor = [UIColor grayColor];
    [moreButton setImage:[UIImage imageNamed:@"icon_more_n@2x.png"] forState:UIControlStateNormal];
    [moreButton setImage:[UIImage imageNamed:@"icon_more_h@2x.png"] forState:UIControlStateHighlighted];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:moreButton];
    
//    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.left.mas_equalTo(@10);
//        make.top.mas_equalTo(@40);
//        make.size.mas_equalTo(CGSizeMake(40, 30));
//    }];
//    [moreButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.top.left.mas_equalTo(@0);
//        make.size.mas_equalTo(CGSizeMake(40, 30));
//    }];
#pragma mark - 按钮方法
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [moreButton addTarget:self action:@selector(moreButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.upButton addTarget:self action:@selector(upButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.nextButton addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.listButton addTarget:self action:@selector(listButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.progressSlider addTarget:self action:@selector(progressSliderAction:) forControlEvents:UIControlEventValueChanged];
    [self.playerView.historyButton addTarget:self action:@selector(historyButtonAction:) forControlEvents:UIControlEventTouchUpInside];
   
    
   
}
- (void)createViews{
    // t
    self.ownerAvator = [[UIImageView alloc]init];
    [self.view addSubview:_ownerAvator];
//    _ownerAvator.backgroundColor = [UIColor clearColor];
    self.ownerAvator.layer.masksToBounds = YES;
    self.ownerAvator.layer.cornerRadius = SCREEN_WIDTH_ZH*0.09;
   // name
    self.ownerName = [AppTools creatLabelWithfont:15.f numberLine:0 textAlignment:0];
    [self.view addSubview:_ownerName];
    // 简介
    self.ownerInfo = [AppTools creatLabelWithfont:13.f numberLine:0 textAlignment:0];
    self.ownerInfo.textColor = [UIColor lightGrayColor];
    [self.view addSubview:_ownerInfo];
    
     [_ownerAvator mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(@20);
        make.bottom.mas_equalTo(@(-20));
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH_ZH*0.18, SCREEN_WIDTH_ZH*0.18));
    }];
    [_ownerName mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(_ownerAvator);
        make.left.equalTo(_ownerAvator.mas_right).offset(15);
        make.right.mas_equalTo(@(-20));
        make.height.mas_equalTo(@30);
    }];
    [_ownerInfo mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(_ownerName);
        make.bottom.mas_equalTo(@(-20));
        make.height.mas_equalTo(@20);
    }];
}
#pragma mark - 返回 更多按钮方法
- (void)backButtonAction:(UIButton *)btn{
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}
- (void)moreButtonAction:(UIButton *)btn{
    
}
#pragma mark - 上一首 下一首 按钮方法
- (void)upButtonAction:(UIButton *)btn{
    if (self.indexRow != 0) {
        self.indexRow = (self.indexRow - 1);
    }
    else
    {
        btn.enabled = NO;
    }
    ZTTrackModel *model = [self.allMusicArray objectAtIndex:self.indexRow];

    self.song_id = model.trackId;

}
//歌曲id
-(void)setSong_id:(NSInteger)song_id
{
    _song_id = song_id;
    if (song_id == 0) {
        
    }else
    {
        [self playMusic];
    }
    if (_indexRow == 0) {
        self.playerView.upButton.enabled = NO;
    }
}


- (void)nextButtonAction:(UIButton *)btn{
    //+1后对总数取余是为了防止点击多次,数组越界
    
    if (self.allMusicArray.count == 0) {
        [self playMusic];
    }
    else
    {
        self.indexRow = (self.indexRow + 1)%self.allMusicArray.count;
        
        //        NSLog(@"indexRow = %ld", (long)self.indexRow);
        //如果歌曲总数大于当前播放的音乐下标
        if (self.indexRow < self.allMusicArray.count) {
            
            ZTTrackModel *modelM = [self.allMusicArray objectAtIndex:self.indexRow];
            self.song_id = modelM.trackId;
            
        }
        else
        {
            //如果总数小于当前下标,直接播放取余数后的.也就是从第一首歌开始播放,用户体验是循环播放了
            [self playMusic];
            
        }
        self.playerView.upButton.enabled = YES;
        
    }

}
#pragma mark - 播放 暂停 按钮方法
- (void)playButtonAction:(UIButton *)btn{
    
    if (self.player.state == STKAudioPlayerStatePlaying) {
        [self.player pause];
        [self.playTimer invalidate];
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_play_n_p@2x.png"] forState:UIControlStateNormal];
        
    }
    else if (self.player.state == STKAudioPlayerStatePaused)
    {
        [self.player resume];
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_pause_n_p@2x.png"] forState:UIControlStateNormal];
        
    }
    else
    {
        [self playMusic];
    }
    
    btn.selected = !btn.selected;
}
#pragma mark - 列表按钮方法
- (void)listButtonAction:(UIButton *)btn{
    
    ZHPlayListViewController *listVC = [[ZHPlayListViewController alloc]init];
    listVC.playListArray = self.allMusicArray;
    [self presentViewController:listVC animated:YES completion:^{
        
        
    }];
}
#pragma mark - 进度按钮方法
- (void)progressSliderAction:(UIButton *)btn{
    //改变播放进度
    [self.player seekToTime:self.playerView.progressSlider.value];
}
#pragma mark - 历史播放按钮方法
- (void)historyButtonAction:(UIButton *)btn{
    ZHPlayListViewController *playListVC = [[ZHPlayListViewController alloc]init];
    playListVC.playListArray = [[ZHFMDB shareFMDB] selectTrackData];
    playListVC.kind = @"播放历史";
    [self presentViewController:playListVC animated:YES completion:^{
        
        
    }];

}

- (void)playMusic
{
    
    NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%ld", (long)self.song_id];
    
//        NSLog(@"zh -- %@", string);
    // 获取数据
    [AppTools getDataWithURL:string Block:^(id result) {
        
        NSMutableDictionary *dictionary = result;
//        NSLog(@"result = %@",dictionary);
        
        ZTAlbumModel *albumModel = [ZTAlbumModel modelWithDictionary:dictionary];
        
        [self.player play:albumModel.playUrl64];
//        NSLog(@"zh===%@",albumModel.playUrl64 );
        [self.playerView.backgroundImageView sd_setImageWithURL:[NSURL URLWithString:albumModel.coverLarge] placeholderImage:PLACEHOLDER_IMAGE];
        [self.playerView.musicImageView sd_setImageWithURL:[NSURL URLWithString:albumModel.coverLarge] placeholderImage:PLACEHOLDER_IMAGE];
        self.title = albumModel.title;
        [self.ownerAvator sd_setImageWithURL:[NSURL URLWithString:albumModel.smallLogo] placeholderImage:PLACEHOLDER_IMAGE];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [self.ownerAvator addGestureRecognizer:tap];
        self.uid = albumModel.uid;
        self.ownerName.text = albumModel.nickname;
        self.ownerInfo.text = albumModel.personInfo;
#pragma mark - 创建定时器
        self.playTimer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
#pragma mark - 记录播放过的音乐
        [[ZHFMDB shareFMDB] deleteByTrackId:albumModel.trackId];
        
        [[ZHFMDB shareFMDB] insertTrackData:albumModel];
        

        
        
        // 通知按钮换图片
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeImage" object:[NSURL URLWithString:albumModel.coverLarge]];
        [[ZHPlayButtonView shareButton].musicBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:albumModel.coverLarge] forState:UIControlStateNormal placeholderImage:PLACEHOLDER_IMAGE];
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_pause_h_p@2x.png"] forState:UIControlStateNormal];

        
    } ErrorBlock:^(NSError *error) {
        
        
    }];
    
    
   
    
    
    
    
}

#pragma mark - 定时器方法
-(void)track
{
    //    NSLog(@"====%@",self.player);
    
    self.playerView.progressSlider.maximumValue = self.player.duration;//音乐总共时长
    self.playerView.progressSlider.value = self.player.progress;//当前进度
    //    NSLog(@"%f", self.playerView.progressSlider.value);
    
    //当前时长progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前分钟
    
    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60;//总秒
    NSInteger durSec = (NSInteger)self.player.duration % 60;//总分钟
    
    self.playerView.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", (long)proMin, (long)proSec, (long)durMin, (long)durSec];
    //    NSLog(@"proMin = %ld proSec = %ld",proMin, proSec);
    
    //    self.playerView.progressSlider
    
    if ((NSInteger)self.playerView.progressSlider.value + 1 == (NSInteger)self.playerView.progressSlider.maximumValue) {
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"playMode"] isEqualToString:@"顺序播放"])
        {
            [self nextButtonAction:nil];
        }
        else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"playMode"] isEqualToString:@"单曲循环"])
        {
            [self playMusic];
            
        }
        else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"playMode"] isEqualToString:@"随机播放"])
        {
            //                NSLog(@"随机播放");
            self.indexRow = arc4random()%(self.allMusicArray.count+1);
            
            ZTTrackModel *singleM = [self.allMusicArray objectAtIndex:self.indexRow];
            NSLog(@"%ld", (long)singleM.trackId);
            self.song_id = singleM.trackId;
            
        }
        
        
        
    }
}

- (void)tapAction:(UIGestureRecognizer *)tap{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
